﻿using System.Collections.Generic;
using DapperLambdaSQL.BuildSQL;
using DapperLambdaSQL.Model;

namespace DapperLambdaSQL.Factory
{
    public class DapperContextFactory
    {
        private static Dictionary<IDbConnectionFactory, ISQLBuilder> sqlBuilderDic;

        static DapperContextFactory()
        {
            sqlBuilderDic = new Dictionary<IDbConnectionFactory, ISQLBuilder>();
        }

        public static DapperContext<T> Create<T>(IDbConnectionFactory connectionFactory) where T : DbModel
        {
            AddConfig(connectionFactory);
            return new DapperContext<T>(sqlBuilderDic[connectionFactory], connectionFactory.CreateConnection());
        }

        private static void AddConfig(IDbConnectionFactory connectionFactory)
        {
            if (sqlBuilderDic.ContainsKey(connectionFactory)) return;

            var sqlBuilder = SQLBuilderFactory.CreateSQLBuilder(connectionFactory);
            sqlBuilderDic.Add(connectionFactory, sqlBuilder);
        }
    }
}